<?php
/**
 *                    _ooOoo_
 *                   o8888888o
 *                   88" . "88
 *                   (| -_- |)
 *                    O\ = /O
 *                ____/`---'\____
 *              .   ' \\| |// `.
 *               / \\||| : |||// \
 *             / _||||| -:- |||||- \
 *               | | \\\ - /// | |
 *             | \_| ''\---/'' | |
 *              \ .-\__ `-` ___/-. /
 *           ___`. .' /--.--\ `. . __
 *        ."" '< `.___\_<|>_/___.' >'"".
 *       | | : `- \`.;`\ _ /`;.`/ - ` : | |
 *         \ \ `-. \_ __\ /__ _/ .-` / /
 * ======`-.____`-.___\_____/___.-`____.-'======
 *                    `=---='
 *
 * .............................................
 *          佛祖保佑             永无BUG
 */
function imagecache($imagecache,$array){
    $template=$array['template'];
    $filename=$array['filename'];
    if(!$filename){
        return config("app.url").'/default.png';
    }
    $filePath="public/".$template.'/'.$filename;
    $trueNamePath="/storage/".$template.$filename;
    if(!file_exists($filePath.'/'.$filename)) {
        if(getImage($template,$filename,$filePath))
            return config("app.url").$trueNamePath;
    }
    return config("app.url").$trueNamePath;
}
function  getImage($template,$filename,$filePath){
    $template = getTemplate($template);
    $path = getImagePath($filename);
    // image manipulation based on callback
    if(!$template||!$path)
        return '';
    $manager = new   \Intervention\Image\ImageManager(Config::get('image'));
    $content = $manager->cache(function ($image) use ($template, $path) {
        if ($template instanceof Closure) {
            // build from closure callback template
            $template($image->make($path));
        } else {
            // build from filter template
            $image->make($path)->filter($template);
        }

    }, config('imagecache.lifetime'));
  return  \Illuminate\Support\Facades\Storage::put($filePath,$content);

}
function getTemplate($template)
{
    $template = config("imagecache.templates.{$template}");

    switch (true) {
        // closure template found
        case is_callable($template):
            return $template;

        // filter template found
        case class_exists($template):
            return new $template;

        default:
            // template not found
            return '';
            break;
    }
}
function getImagePath($filename)
{
    // find file
    foreach (config('imagecache.paths') as $path) {
        // don't allow '..' in filenames
        $image_path = $path.'/'.str_replace('..', '', $filename);
        if (file_exists($image_path) && is_file($image_path)) {
            // file found
            return $image_path;
        }
    }

    // file not found
   return '';
}
